package com.ywgt.controller;

import com.github.pagehelper.Page;
import com.ywgt.pojo.Keyword;
import com.ywgt.pojo.SearchHistory;
import com.ywgt.service.KeywordService;
import com.ywgt.service.SearchHistoryService;
import com.ywgt.util.ResponseUtil;
import io.swagger.annotations.ApiModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@CrossOrigin
@RestController
@RequestMapping("/wx/search")
@ApiModel("商品页面")
public class SearchController {

    @Autowired
    KeywordService keywordService;

    @Autowired
    SearchHistoryService searchHistoryService;


    @GetMapping("/index")
    public Object index(Integer userId){
        List<Keyword> keywords = keywordService.list();
        List<Keyword> hotKeywordList = keywords.stream().filter(keyword -> keyword.getIsHot()).collect(Collectors.toList());
        Stream<Keyword> defaultKeyword = keywords.stream().filter(keyword -> keyword.getIsDefault());
        List<SearchHistory> historyList=new ArrayList<>();
        if(userId!=null){
            Page<SearchHistory> searchHistories = searchHistoryService.getHistories(userId, null, 1, 20, "add_time", "desc");
            historyList=searchHistories.getResult();
        }
        Map<String, Object> data = new HashMap<>();
        data.put("defaultKeyword", defaultKeyword);
        data.put("historyKeywordList", historyList);
        data.put("hotKeywordList", hotKeywordList);
        return ResponseUtil.ok(data);
    }

    @GetMapping("/helper")
    public Object helper(@NotNull String keyword, @RequestParam(defaultValue = "1") Integer page,
                         @RequestParam(defaultValue = "10") Integer size){
        Page<Keyword> keywords = keywordService.getKeywords(keyword, page, size, "add_time", "desc");
        List<Keyword> items = keywords.getResult();
        List<String> keyList = items.stream().map(a -> a.getKeyword()).collect(Collectors.toList());
        String keys[]=new String[keyList.size()];
        int index=0;
        for (String s : keyList) {
            keys[index]=s;
            index++;
        }
        return ResponseUtil.ok(keys);
    }
}
